use graphics::cosmic_text::Color;
use graphics::piet::{Text, TextLayout as PietTextLayout, TextLayoutBuilder};
use graphics::{piet, Frame, Size, TextLayout, Transform3D};

use crate::contexts::LifeCycleCtx;
use crate::event::{Event, LifeCycle};
use crate::id::IdPath;
use crate::widget::Widget;

pub struct Label {
    id_path: IdPath,
    pub text: String,
    pub color: [f64; 4],
    layout: Option<TextLayout>,
}

impl Label {
    pub fn new(id_path: IdPath, text: String, color: [f64; 4]) -> Self {
        Self {
            id_path,
            text,
            color,
            layout: None,
        }
    }
}

impl Widget for Label {
    fn event(&mut self, _cx: &mut crate::contexts::EventCtx, _event: &Event) {}

    fn paint(&mut self, _cx: &mut crate::contexts::PaintCtx, g: &mut Frame) {
        if let Some(layout) = &self.layout {
            g.draw_text(layout, Color::rgb(0, 0, 0), Transform3D::identity())
        }
    }

    fn layout(&mut self, cx: &mut crate::contexts::LayoutCtx) -> Size {
        let layout_builder = cx.brush_cx.new_text_layout(self.text.to_string());
        let layout = layout_builder
            .text_color(piet::Color::rgb(
                self.color[0],
                self.color[1],
                self.color[2],
            ))
            .build()
            .unwrap();
        let size = Size::new(layout.size().width as f32, layout.size().height as f32);
        self.layout = Some(layout);
        size
    }

    fn lifecycle(&mut self, _cx: &mut LifeCycleCtx, _event: &LifeCycle) {}
}
